package com.itany.boot.service.Impl;
//分页插件提供
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.boot.constant.DictConstant;
import com.itany.boot.constant.StatusConstant;
import com.itany.boot.dao.UserMapper;
import com.itany.boot.entity.User;
import com.itany.boot.entity.UserExample;
import com.itany.boot.exception.AdminUserException;
import com.itany.boot.exception.CodeErrorException;
import com.itany.boot.exception.MD5ErrorException;
import com.itany.boot.exception.RequestParameterErrorException;
import com.itany.boot.service.AdminUserService;
import com.itany.boot.util.MD5Util;
import com.itany.boot.util.ParameterUtil;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
//注解bean
@Service
//管理事务
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class AdminUserServiceImpl implements AdminUserService {
    @Autowired
    private UserMapper userMapper;

    //只读事务
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User login(String loginName, String password, String code, String image) throws RequestParameterErrorException, CodeErrorException, MD5ErrorException, AdminUserException {
//    参数校验
        if (ParameterUtil.isNull(loginName) || ParameterUtil.isNull(password) || ParameterUtil.isNull(code) || ParameterUtil.isNull(image)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
//    判断验证码
        if (!code.equals(image)) {
            throw new CodeErrorException("验证码错误");
        }
//    登录查询，账号密码，是否在职，要求必须在职
        UserExample example = new UserExample();
        example.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password))
                .andStatusEqualTo(StatusConstant.USER_STATUS_ENABLED);//员工在职


        List<User> users = userMapper.selectByExample(example);
        if (users.isEmpty()) {
            throw new RequestParameterErrorException("用户名或密码错误");
        }
        User user = users.get(0);
//    角色校验
        if (!"admin".equals(user.getRole())) {
            throw new AdminUserException("用户不是管理员");
        }

//        登录成功后更新登录日期
        Date currentTime=new Date();
        userMapper.updateLoginDate(user.getId(),currentTime);

        return user;
    }
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
//    userParam接收前台传过来的参数
    public PageInfo<User> findByParams(User userParam, String pageNo, String pageSize) {
        if(ParameterUtil.isNull(pageNo)){
//            为空默认在第一页
            pageNo= DictConstant.USER_TYPE_DEFAULT_PAGE_NO;
        }
        if(ParameterUtil.isNull(pageSize)){
            pageSize=DictConstant.USER_TYPE_DEFAULT_PAGE_SIZE;
        }
//        通过MyBatis分页插件PageHelper实现分页功能
//        该插件实现分页，三步走
//        1.设置分页信息,String转为int
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
//        2.获取分页数据
        List<User> users=userMapper.selectByParams(userParam);
//        3.封装分页对象
        PageInfo<User> userPage = new PageInfo<>(users);
        return userPage;
    }
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User findById(String id) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(id)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        return userMapper.selectByPrimaryKey(Integer.parseInt(id));
    }

    @Override
    public void modifyUser(String id, String nickname, String role, String password, String email) throws RequestParameterErrorException {
//        参数校验
        if(ParameterUtil.isNull(id)||ParameterUtil.isNull(nickname)||ParameterUtil.isNull(role)||ParameterUtil.isNull(email)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setNickname(nickname);
        user.setRole(role);
        user.setEmail(email);

        // 如果密码不为空则更新密码（需要加密）
        if(!ParameterUtil.isNull(password)) {
            user.setPassword(MD5Util.md5(password));
        }
        // 执行更新操作
        userMapper.updateByPrimaryKeySelective(user);

    }

    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
                if(ParameterUtil.isNull(id)||ParameterUtil.isNull(status)){
                    throw new RequestParameterErrorException("请求参数有误");
                }
                User user=new User();
                user.setId(Integer.parseInt(id));
                user.setStatus(Integer.parseInt(status));
        if (user.getStatus() == StatusConstant.USER_STATUS_ENABLED) {
            // 如果是启用,则修改为禁用
            user.setStatus(StatusConstant.USER_STATUS_DISABLED);
        } else {
            // 否则修改为启用
            user.setStatus(StatusConstant.USER_STATUS_ENABLED);
        }
        // 执行修改操作
        userMapper.updateByPrimaryKeySelective(user);

    }
}
